package com.yanxinim.cn.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.j256.ormlite.stmt.query.In;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.store.StoreOrderDetailsActivity;
import com.yanxinim.cn.store.adapter.OrderAdapter;
import com.yanxinim.cn.store.bean.OrderInfo;
import com.yanxinim.cn.ui.base.EasyFragment;
import com.yanxinim.cn.util.JsonTool;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OrderListFragment extends EasyFragment {
    private SmartRefreshLayout srlRefresh;
    private RecyclerView rvNewsList;
    private ImageView ivNothing;
    private Context context;

    private String status;
    private String userId;
    private int pageIndex;
    private OrderAdapter orderAdapter;
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            int page = msg.arg1;
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("resultCode") == 1) {
                JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("data"));
                List<OrderInfo> orderInfos = JsonTool.jsonToList(jsonObject1.getString("pageData"), OrderInfo.class);
                if (orderInfos == null || orderInfos.size() == 0) {
                    srlRefresh.setEnableLoadMore(false);
                    if (page == 0) {
                        ivNothing.setVisibility(View.VISIBLE);
                        if (orderAdapter != null) {
                            orderAdapter.cleanAll();
                        }
                    }
                    return;
                }
                ivNothing.setVisibility(View.GONE);

                if (page == 0) {
                    if (orderAdapter != null) {
                        orderAdapter.cleanAll();
                    }
                    orderAdapter = new OrderAdapter(context, orderInfos);
                    orderAdapter.setItemOnClickListener((newType, position) -> {
                        Intent intent = new Intent(context, StoreOrderDetailsActivity.class);
                        intent.putExtra("orderInfo", newType);
                        startActivity(intent);
                    });
                    rvNewsList.setAdapter(orderAdapter);
                } else {
                    if (orderAdapter != null) {
                        orderAdapter.addAllData(orderInfos);
                    }
                }
                if (orderInfos.size() < 10) {
                    srlRefresh.setEnableLoadMore(false);
                } else {
                    srlRefresh.setEnableLoadMore(true);
                }
            }

            srlRefresh.finishLoadMore();
            srlRefresh.finishRefresh();
        }
    };

    public OrderListFragment() {
    }

    public static OrderListFragment getInstance(String status, String userId) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("status", status);//0待付款，1待发货，2已发货，3已完成，4已取消，5退款中
        bundle.putString("userId", userId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.a_news_list_fragment;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        context = getActivity();
        Bundle bundle = getArguments();
        if (bundle != null) {
            status = bundle.getString("status");
            userId = bundle.getString("userId");
        }
        srlRefresh = findViewById(R.id.srl_refresh);
        rvNewsList = findViewById(R.id.rv_news_list);
        ivNothing = findViewById(R.id.iv_nothing);

        rvNewsList.setLayoutManager(new LinearLayoutManager(context));
        srlRefresh.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            if (status.equals("-1"))
                initData(status);
            else initData2(status);
        });
        srlRefresh.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            if (status.equals("-1"))
                initData(status);
            else initData2(status);
        });
        if (status.equals("-1"))
            initData(status);
        else initData2(status);
    }

    public void refreshData() {
        if (srlRefresh != null)
            srlRefresh.autoRefresh();
    }

    private void initData(String status) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", "10");

        HttpUtils.post().url(AppConfig.STORE_ALL_ORDER)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Message message = new Message();
                message.what = 1;
                message.arg1 = pageIndex;
                message.obj = result;
                handler.sendMessage(message);

            }
        });
    }

    private void initData2(String status) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("orderState", status);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", "10");

        HttpUtils.post().url(AppConfig.STORE_ORDER_STATES)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Message message = new Message();
                message.what = 1;
                message.arg1 = pageIndex;
                message.obj = result;
                handler.sendMessage(message);

            }
        });
    }


}
